package kernel.udp.requests;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class RequestHandler extends Thread {

	String reqString;
	InetAddress client;
	DatagramSocket socket;
	int client_port;
	HandlerFinder HandlerManager;
	
	public RequestHandler(String request, DatagramSocket Socket, InetAddress Client, int clientPort, HandlerFinder HandlerMgr){
		
		reqString = request;
		client = Client;
		socket = Socket;
		client_port = clientPort;
		HandlerManager = HandlerMgr;
		
	}

	public void run(){
		
		try{
			
			Request myReq = new Request(reqString);
			
			// - PROCESSING
			//System.out.println("[ "+"UDP CLIENT"+" ] "+"[ Incoming ] [ Source = "+client.toString().substring(1)+":"+client_port+" ]");
			//System.out.println("[ "+"UDP CLIENT"+" ] "+"[ Incoming ] [ Request Handler = "+myReq.ModuleName+"."+myReq.ServiceName+" ]");
			Class[] pTypes = myReq.ParamTypes();
			
			String message = myReq.reqNo+";"+(String) HandlerManager.invoke(myReq.ModuleName, myReq.ServiceName, pTypes, myReq.Parameters);

			//System.out.println("[ "+"UDP CLIENT"+" ] "+"[ Outgoing ] [ Dest.  = "+client.toString().substring(1)+":"+client_port+" ] [ Reply Contents  = "+message+" ]");
			// - Send information back to the client			
			byte[] buffer = new byte[4096];
			buffer = message.getBytes() ;
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length, client, client_port);
			socket.send(packet);
			
		}
		catch(Exception e){			
			e.printStackTrace();
		}
		
	}
}
